//
//  XLRecVoiceChatVC.m
//  XiangLove
//
//  Created by 李传坤 on 2018/8/8.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLRecVoiceChatVC.h"
#import "MZTimerLabel.h"
#import "PeerModel.h"
#import "KeyboardView.h"
#import "GiftModel.h"
#import "YFGIFImageView.h"
#import "NSDictionary+Ext.h"
#import "BeautySettingPanel.h"
#import <TXCVideoPreprocessor.h>
#import <ReactiveCocoa.h>
#import "TopUpViewController.h"
#import "XLHTTPSessionManager.h"
#import <ReactiveCocoa.h>
#import "XLTalkThemeSheetView.h"
//#import "XLHostSideIncomeDetailsVC.h"
#import <Lottie/Lottie.h>
#import "UIImage+WebP.h"
@interface XLRecVoiceChatVC ()<TILCallNotificationListener,TILCallStatusListener,TILCallMessageListener,TILCallMemberEventListener,AVAudioPlayerDelegate,KeyboardViewDelegate,TXIVideoPreprocessorDelegate,MZTimerLabelDelegate>
{
    AVAudioPlayer * _audioPlayer;
}
@property (nonatomic, strong) TILC2CCall      *call;
@property (nonatomic, strong) UIImageView     *backimage;
@property (nonatomic, strong) UIImageView     *headImae;
@property (nonatomic, strong) UILabel         *nameLabel;
@property (nonatomic, strong) UILabel         *gradeLabel;
@property (nonatomic, strong) UILabel         *detailLabel;
@property (nonatomic, strong) UIButton        *closeBtn;
@property (nonatomic, strong) UIButton        *recvBtn;

@property (nonatomic, strong) UILabel         *closeLab;
@property (nonatomic, strong) UIButton        *cinemaBtn;
@property (nonatomic, strong) UILabel         *cinemaLab;
@property (nonatomic, strong) UIButton        *jietingButton;//接听button
@property (nonatomic, strong) UIButton        *followButton;//接听button
@property (nonatomic, strong) UILabel         *jietingLab;//接听label
@property (nonatomic, strong) UIButton        *micButton;//micbutton
@property (nonatomic, strong) UILabel         *micLab;//miclabel
@property (nonatomic, strong) UIButton        *miantiButton;//免提button
@property (nonatomic, strong) UILabel         *miantiLab;//免提label
@property (nonatomic, strong) UILabel         *inforLabel;//xinxi
@property (nonatomic, assign) BOOL             isring;
@property (nonatomic, assign) BOOL             isfollow;
@property (nonatomic, strong) MZTimerLabel    *recvtimer;
@property (nonatomic, strong) NSTimer         *heartChcek;         //心跳OBJC
@property (nonatomic, assign) BOOL             isBaseDid;

@property (nonatomic, strong) PeerModel       *peermodel;

@property (nonatomic, strong) NSString        *myId;
//@property (nonatomic, strong) LiveUIRightView *RightView;


@property (nonatomic, strong) UIButton        *giftBtn;
@property (nonatomic, strong) UIButton           *chatThemeBtn;

@property (nonatomic, strong) UILabel         *giftLab;
@property (nonatomic, strong) KeyboardView    *keyboardView;
@property (nonatomic, strong)NSMutableArray   *senderGiftArr;
@property (nonatomic, strong) YFGIFImageView  *gifview;
@property (nonatomic, strong) XLTalkThemeSheetView       *TalkThemeSheetView;
@property (nonatomic, strong) UIImageView     *gifImageView;

@property (nonatomic, assign) BOOL             isReceived;
@property (nonatomic, assign) BOOL             isEnderMoney;


@property (nonatomic, strong) BeautySettingPanel *vBeauty;
@property (nonatomic, strong) UIButton *btnCamera;

@property (nonatomic, strong) TXCVideoPreprocessor *preProcessor;
@property (nonatomic, assign) Byte           *processorBytes;

@property (nonatomic, assign) TXEBeautyStyle  beautyType;
@property (nonatomic, assign) NSInteger       BeautyLevel;
@property (nonatomic, assign) NSInteger       WhitenessLevel;
@property (nonatomic, assign) NSInteger       RuddinessLevel;
@property (nonatomic, assign) TXEFilterType   FilterType;
@property (nonatomic, strong) UIImage        *FilterUIImage;
@property (nonatomic, assign) CGFloat         FilterMixLevel;
@property (nonatomic, copy  ) NSString       *GreenScreenFile;
@property (nonatomic, assign) NSInteger       EyeScaleLevel;
@property (nonatomic, assign) NSInteger       FaceSlimLevel;
@property (nonatomic, assign) NSInteger       FaceBeautyLevel;
@property (nonatomic, assign) NSInteger       FaceVLevel;
@property (nonatomic, assign) NSInteger       ChinLevel;
@property (nonatomic, assign) NSInteger       FaceShortLevel;
@property (nonatomic, assign) NSInteger       NoseSlimLevel;
@property (nonatomic, copy  ) NSString       *MotionTemplate;
@property (nonatomic, strong) UIView         *recevBottomView;
@property (nonatomic, assign) BOOL                Animalfinish;//判断动画是否完成;
@property (nonatomic, strong) LOTAnimationView *launchAnimation;

@property (nonatomic, assign) BOOL                               giftAnimalFinish;
@end

@implementation XLRecVoiceChatVC
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    if (self.isEnderMoney == YES) {
        [_audioPlayer stop];
        self.call = nil;_Animalfinish = YES;
        [self.heartChcek invalidate];
        self.heartChcek = nil;
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(heartbeatCallup) object:nil];
    //    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(heartbeatCallupAPI) object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:BMHRefreshUserInfo object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reaciveGiftMessage:)name:@"videoGiftMessage" object:nil];//礼物发送
    
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
}

- (void)hangupWithNoManny{
    [self callMakeEndCall:@"14"];
    [self selfDismiss];
    //    [HelpTool startTipViewWithText:@"用户余额不足" duration:2.0f type:kTipViewTypeNone];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.isEnderMoney = YES;
}
- (void)viewDidLoad{
    [super viewDidLoad];
    _giftAnimalFinish = YES;
    self.isBaseDid = NO;_Animalfinish = YES;
    self.fd_prefersNavigationBarHidden = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reaciveGiftMessage:)name:@"videoGiftMessage" object:nil];//礼物发送
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hangupWithNoManny) name:@"hangupYuebuzu" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reacveQuestion:)name:@"ChatThemeAndQuestion" object:nil];//话题指令
    [[NSNotificationCenter defaultCenter] postNotificationName:@"callreceive" object:nil];
    [self checkMiroPhone];
    
    self.preProcessor = [[TXCVideoPreprocessor alloc] init];
    [self.preProcessor setDelegate:self];
    self.view.backgroundColor = [UIColor blackColor];
    [self makecallwaitPlay];
    [self otherChatInfo];
    [self setButtonEnable:YES];
    [self initCall];
    [self addSubView];
    self.senderGiftArr = [NSMutableArray array];
    [self getFlowerList];
    
    _conversation = [[IMAPlatformxl sharedInstance].conversationMgr chatWith:_invite.sponsorId];
    
    _myId = [[ILiveLoginManager getInstance] getLoginId];
    [[ILiveRoomManager getInstance] setLocalVideoDelegate:self];
    
    _receiverKVO = [FBKVOController controllerWithObserver:self];
    _conversation = [[IMAPlatformxl sharedInstance].conversationMgr chatWith:self.peerId];
    __weak XLRecVoiceChatVC *ws = self;
    @weakify(self)
    _conversation.receiveMsg = ^(NSArray *imamsgList, BOOL succ, IMAMsg *msg) {
        
        TIMElem *meaage = [msg.msg getElem:0];
        if ([meaage isKindOfClass:[TIMCustomElem class]]){
            TIMCustomElem *elem = (TIMCustomElem *)[msg.msg getElem:0];
            CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
            
            if (elemCmd.msgType == 3) {
                
                if ([elemCmd.giftBubbleImage rangeOfString:@"gif"].location != NSNotFound ) {
//                    [ws addGifPicWithIndexXX:elemCmd.giftBubbleImage withName:elemCmd.giftName];
                    
                }else {
//                    [ws addGifImageView:elemCmd.giftMsgImage withName:elemCmd.giftName];
                    
                }
            }else if (elemCmd.msgType == 9){
                @strongify(self)
            }
            
        }
        
    };
    if (self.peermodel.isMatchCall == 1) {
        [self handleRecOrMicButton:self.jietingButton];
    }
}




-(void)makecallwaitPlay
{
    NSString *audioFile=[[NSBundle mainBundle] pathForResource:@"微信语音提示音" ofType:@"mp3"];
    NSURL *fileUrl=[NSURL fileURLWithPath:audioFile];
    NSError *error;
    _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error];
    _audioPlayer.delegate = self;
    _audioPlayer.volume =1.0;
    [_audioPlayer prepareToPlay];
    if (_audioPlayer == nil) {
        
        NSLog(@"播放音频%@", [error description]);
        
    }
    else{
        [self palyOne];
        
    }
}

-(void)palyOne
{
    _audioPlayer.numberOfLoops = 1;
    if (!_audioPlayer.isPlaying) [_audioPlayer play];
    else _audioPlayer.currentTime = 0.0f;
    
}

- (void)stop
{
    [_audioPlayer stop];
    
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)player successfully:(BOOL)flag{
    //播放结束时执行的动作
    NSLog(@"===播放结束了====");
    [self palyOne];
    
    
}


-(void)otherChatInfo{
    NSDictionary * otherInfoDic =[NSDictionary dictionaryWithJsonString:self.invite.custom];
    self.peermodel = [[PeerModel alloc] initWithDic:otherInfoDic];
    self.callid = [NSString stringWithFormat:@"%d",self.peermodel.newRecordId];
}


- (void)reacveQuestion:(NSNotification *)infor{
    NSDictionary *dic = infor.userInfo;
    if (_Animalfinish == YES) {
        [self amimalChatQuestion: dic[@"chatQuestion"]];
    }
}

#pragma make - ******makeUI
- (void)addSubView {
    
    UILabel *errLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, XQScreenW, XQScreenH)];
    errLabel.textAlignment = NSTextAlignmentCenter;
    errLabel.font = [UIFont systemFontOfSize:14];
    errLabel.numberOfLines = 1;
    errLabel.textColor = [UIColor whiteColor];
    errLabel.text = NSUser_object(UserNick);
    [self.view addSubview:errLabel];
    self.errLabel = errLabel;
    
    UIImageView *backimage = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, [UIScreen mainScreen].bounds.size.width, XQScreenH)];
    backimage.image = [UIImage imageNamed:@"video_bg_yaoqing_n.png"];
    backimage.backgroundColor = [UIColor clearColor];
    backimage.userInteractionEnabled = YES;
    self.backimage = backimage;
    _launchAnimation = [LOTAnimationView animationNamed:@"soundWave"];
    _launchAnimation.cacheEnable = NO;
    _launchAnimation.frame = CGRectMake(ScreenWidth/2-130, ScreenHeight/2 - 200, 260, 260);
    _launchAnimation.contentMode = UIViewContentModeScaleToFill;
    _launchAnimation.animationSpeed = 1;_launchAnimation.loopAnimation = YES;
    [_launchAnimation play];
    [backimage addSubview:_launchAnimation];
    UIImageView *headImae = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenWidth/2 - 60,ScreenHeight/2 - 130, 120, 120)];
    headImae.backgroundColor = [UIColor whiteColor];
    headImae.layer.cornerRadius = 60;
    headImae.layer.masksToBounds = YES;
    [headImae sd_setImageWithURL:[NSURL URLWithString:self.peermodel.headimg] placeholderImage:[UIImage imageNamed:@"BeautyPlaceholder"]];
    [backimage addSubview:headImae];
    self.headImae = headImae;
    
    //关注按钮
    UIButton *followButton = [UIButton buttonWithType:UIButtonTypeCustom];
    followButton.frame = CGRectMake(ScreenWidth/2 - 15,ScreenHeight/2 - 30, 30, 30);
    [followButton setImage:[UIImage imageNamed:@"video_icon_guanzhu_n"] forState:UIControlStateNormal];
    [followButton addTarget:self action:@selector(followBtn) forControlEvents:UIControlEventTouchUpInside];
    followButton.hidden = YES;
    [backimage addSubview:followButton];
    self.followButton = followButton;
    
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.textAlignment = NSTextAlignmentLeft;
    nameLabel.font = [UIFont systemFontOfSize:21];
    nameLabel.numberOfLines = 1;
    nameLabel.textColor = [UIColor whiteColor];
    nameLabel.text = self.peermodel.name;
    [backimage addSubview:nameLabel];
    nameLabel.frame = CGRectMake(20 ,50, [UIScreen mainScreen].bounds.size.width, 40);
    self.nameLabel = nameLabel;
    UILabel *inforLabel = [[UILabel alloc] init];
    inforLabel.textAlignment = NSTextAlignmentCenter;
    inforLabel.font = [UIFont systemFontOfSize:15];
    inforLabel.textColor = [UIColor whiteColor];
    inforLabel.text = self.peermodel.name;
    [backimage addSubview:inforLabel];
    inforLabel.hidden = YES;
    self.inforLabel = inforLabel;
   
    UILabel *detailLabel = [[UILabel alloc] init];
    detailLabel.frame = CGRectMake(20, 90, [UIScreen mainScreen].bounds.size.width, 20);
    detailLabel.textAlignment = NSTextAlignmentLeft;
    detailLabel.font = [UIFont systemFontOfSize:14];
    detailLabel.numberOfLines = 1;
    detailLabel.textColor = [UIColor whiteColor];
    detailLabel.text =@"邀请您语音通话...";
    self.detailLabel = detailLabel;
    [backimage addSubview:detailLabel];
    [self.view addSubview:backimage];
    
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 100, [UIScreen mainScreen].bounds.size.width, 100)];
    bottomView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:bottomView];
    UIView *middleView = [[UIView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 200, [UIScreen mainScreen].bounds.size.width, 100)];
    middleView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:middleView];
    
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    closeBtn.frame = CGRectMake(SCREEN_WIDTH/4-15, SCREEN_HEIGHT - 120, 60, 60);
    [closeBtn setImage:[UIImage imageNamed:@"video_icon_guaduan_n"] forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(handleCloseBtn:) forControlEvents:UIControlEventTouchUpInside];
    self.closeBtn = closeBtn;
    
    UILabel *closeLab = [[UILabel alloc] init];
    closeLab.frame = CGRectMake(SCREEN_WIDTH/4-20, SCREEN_HEIGHT - 50, 70, 20);
    closeLab.text = @"拒绝";
    closeLab.textAlignment = NSTextAlignmentCenter;
    closeLab.font = [UIFont systemFontOfSize:13];
    closeLab.textColor = [UIColor whiteColor];
    self.closeLab = closeLab;
    
    [self.view addSubview:closeLab];
    [self.view addSubview:closeBtn];
    //接听
    UIButton *jietingButton = [UIButton buttonWithType:UIButtonTypeCustom];
    jietingButton.frame = CGRectMake(SCREEN_WIDTH/4*3-45, SCREEN_HEIGHT - 120, 60, 60);
    [jietingButton setImage:[UIImage imageNamed:@"voice_icon_voicejieting_n"] forState:UIControlStateNormal];
    self.jietingButton = jietingButton;
    
    [jietingButton addTarget:self action:@selector(handleRecOrMicButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:jietingButton];
    //接听label
    UILabel *jietingLab = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/4*3-50, SCREEN_HEIGHT - 50, 70, 20)];
    jietingLab.text = @"接听";
    jietingLab.textAlignment = NSTextAlignmentCenter;
    jietingLab.font = [UIFont systemFontOfSize:13];
    jietingLab.textColor = [UIColor whiteColor];
    self.jietingLab = jietingLab;
    
    [self.view addSubview:jietingLab];
    
    //    closeBtn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width/ 2 - 35 - 75, 80, 70, 70);
    //    closeLab.frame = CGRectMake([UIScreen mainScreen].bounds.size.width/ 2 - 35 - 75, 160, 70, 20);
    
    
    //    UIButton *cinemaBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //    cinemaBtn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width/ 2 + 20 , 80, 70, 70);
    //    [cinemaBtn setImage:[UIImage imageNamed:@"SwitchCamera"] forState:UIControlStateNormal];
    //    cinemaBtn.hidden = YES;
    //    cinemaBtn.layer.masksToBounds = YES;
    //    cinemaBtn.layer.cornerRadius = 35;
    //    self.cinemaBtn = cinemaBtn;
    //    //    self.cinemaBtn.hidden = YES;
    //    [cinemaBtn addTarget:self action:@selector(handleCinemaBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    //礼物
    //    UIButton *giftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //    giftBtn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 50, 30, 40, 40);
    //    [giftBtn setImage:[UIImage imageNamed:@"SwitchGift"] forState:UIControlStateNormal];
    //    giftBtn.hidden = YES;
    //    self.giftBtn = giftBtn;
    //    [giftBtn addTarget:self action:@selector(handleGiftBtn:) forControlEvents:UIControlEventTouchUpInside];
    //    [bottomView addSubview:giftBtn];
    
    
   
    //话题
    UIButton *chatThemeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    chatThemeBtn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 100, 30, 40, 40);
    [chatThemeBtn setImage:[UIImage imageNamed:@"video_icon_huati_n"] forState:UIControlStateNormal];
    chatThemeBtn.hidden = YES;
    self.chatThemeBtn = chatThemeBtn;
    [chatThemeBtn addTarget:self action:@selector(showChatChemeView:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:chatThemeBtn];
    self.recevBottomView = bottomView;
    //礼物
    UIButton *giftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    giftBtn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 50, 30, 40, 40);
    [giftBtn setImage:[UIImage imageNamed:@"video_icon_liwu_n"] forState:UIControlStateNormal];
    giftBtn.hidden = YES;
    self.giftBtn = giftBtn;
    [giftBtn addTarget:self action:@selector(handleGiftBtn:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:giftBtn];
    
    //免提
    UIButton *miantiButton = [UIButton buttonWithType:UIButtonTypeCustom];
    miantiButton.frame = CGRectMake(ScreenWidth/ 3 - 35 , 0, 70, 70);
    [miantiButton setImage:[UIImage imageNamed:@"video_icon_handfree_n"] forState:UIControlStateNormal];
    miantiButton.layer.masksToBounds = YES;
    miantiButton.layer.cornerRadius = 35;
    miantiButton.hidden = YES;
    [miantiButton addTarget:self action:@selector(handleSpeakerButton:) forControlEvents:UIControlEventTouchUpInside];
    self.miantiButton = miantiButton;
    [middleView addSubview:miantiButton];
    //免提
    UILabel *miantiLab = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth/3 - 35, 70, 70, 20)];
    miantiLab.text = @"免提";
    miantiLab.textAlignment = NSTextAlignmentCenter;
    miantiLab.font = [UIFont systemFontOfSize:13];
    miantiLab.textColor = [UIColor whiteColor];
    miantiLab.hidden = YES;
    self.miantiLab = miantiLab;
    [middleView addSubview:miantiLab];
    //麦克风
    UIButton *micButton = [UIButton buttonWithType:UIButtonTypeCustom];
    micButton.frame = CGRectMake([UIScreen mainScreen].bounds.size.width/ 3 *2 - 35 , 0, 70, 70);
    [micButton setImage:[UIImage imageNamed:@"video_icon_quite_n"] forState:UIControlStateNormal];
    micButton.layer.masksToBounds = YES;
    micButton.layer.cornerRadius = 35;
    //micButton.hidden = YES;
    [micButton addTarget:self action:@selector(handleMicButton:) forControlEvents:UIControlEventTouchUpInside];
    self.micButton = micButton;
    [middleView addSubview:micButton];
    //麦克风
    UILabel *micLab = [[UILabel alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width/ 3 *2 - 35, 70, 70, 20)];
    micLab.text = @"静音";
    micLab.textAlignment = NSTextAlignmentCenter;
    micLab.font = [UIFont systemFontOfSize:13];
    micLab.textColor = [UIColor whiteColor];
    micLab.hidden = YES;
    self.micLab = micLab;
    [middleView addSubview:micLab];
    [self getUserInfor];
    
}
- (void)followBtn{
    [[[XLHTTPSessionManager sharedManager] XLV2POST:@"/api/v2/UserInfo/Follow" parameters:@{@"FollowId":self.peerId,@"FansId":[XLAccountManager shareInstance].model.Id} resultClass:nil] subscribeNext:^(id x) {
        self.followButton.hidden = YES;
        [MBProgressHUD showContent:@"已关注"];
        NSLog(@"关注成功%@",x);
    } error:^(NSError *error) {
        NSLog(@"关注失败%@",error);
        
    }];
}
- (void)getUserInfor{
    [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/Api/v2/VideoChat/GetVoiceUserInfo" parameters:@{@"userId":_peerId} resultClass:nil] subscribeNext:^(id x) {
        NSDictionary *dic = x;
        _isfollow = [dic[@"IsAttention"] integerValue];
        if (![dic[@"HostCity"] isKindOfClass:[NSNull class]]) {
            NSString *sex = [dic[@"Sex"] integerValue] == 1 ? @"男":@"女";
            _inforLabel.text = [NSString stringWithFormat:@"%@  %@",dic[@"HostCity"],sex];
            
        }
    } error:^(NSError *error) {
        
    }];
}
- (void)onBtnCameraClicked {
    [self.call switchCamera:^(TILCallError *err) {
        
    }];
}
#pragma mark -  **********充值跳转
-(void)keyboardViewChargeBtn{
    TopUpViewController *topVC = [[TopUpViewController alloc] initWithBeautyid:[[NSUserDefaults standardUserDefaults] objectForKey:UserID]];
    topVC.In_purchase = NO;
    topVC.backActionBlock = ^() {
        [self dismissViewControllerAnimated:YES completion:NULL];
    };
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:topVC];
    [self presentViewController:nav animated:YES completion:nil];
}
#pragma mark -  **********礼物展示
- (void)handleGiftBtn:(UIButton *)sender {
    [_TalkThemeSheetView removeFromSuperview];
    self.keyboardView = [[KeyboardView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.height) array:self.senderGiftArr WithColor:RGBA_HEX(0x0C0D10, 0.95) withIslive:NO];
    self.keyboardView.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.3];
    
    self.keyboardView.mydelegate = self;
    
    [self.view addSubview:self.keyboardView];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hide)];
    [self.keyboardView addGestureRecognizer:tapGesture];
    
}

#pragma mark -  **********送礼物
- (void)keyboardViewDidSendUrl:(NSString *)imageUrl moverImageUrl:(NSString *)moverUrl name:(NSString *)name price:(float)price giftID:(NSInteger)giftID {
    if (_giftAnimalFinish == YES) {
        _giftAnimalFinish = NO;
        
        NSLog(@"vvvvvvvv == %@ --- %@", imageUrl, [[NSUserDefaults standardUserDefaults] objectForKey:UserID]);
        NSDate *now = [NSDate date];
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = kBMHRequestTimeFormat;
        NSString *sTime = [fmt stringFromDate:now];
        NSString *objID = @"0";
        NSString *publicKey = @"BMH2014YDYWB";
        NSString *nat = [NSString stringWithFormat:@"%@%@%@%@",objID,[[NSUserDefaults standardUserDefaults] objectForKey:UserID], publicKey, sTime];
        nat = [nat md5Encrypt];
        NSDate * senddate=[NSDate date];
        NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
        NSString *locationString = [dateformatter stringFromDate:senddate];
        
        NSDictionary *  dicRegister= [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"type",locationString,@"Timestamp",nat,@"Appsign",[NSString stringWithFormat:@"%ld", (long)giftID],@"giftId",[[NSUserDefaults standardUserDefaults] objectForKey:UserID], @"giveUserId",self.peerId, @"giftsUserId", [NSString stringWithFormat:@"%f", price], @"giftPrice", @"1", @"giftNumber",@"",@"Intro",_callid,@"DynamicID", nil];
        [[[XLHTTPSessionManager sharedManager]XLV2POST:@"/Api/v2/Gift/GiveGift" parameters:dicRegister resultClass:nil] subscribeNext:^(id x) {
            NSLog(@"礼物僧送==-=-=-=-=-=-%@", x);
            
            if (x != nil) {
                //            IMAMsg *msgs = [IMAMsg msgWithCustom:3 priceStr:[NSString stringWithFormat:@"%0.f", price * 10] giftBubbleImageUrl:moverUrl giftMsgImageUrl:imageUrl NameStr:name];
                //            [self giftMessageOfsenderComment:msgs];
                if (giftID != 109) {
                    [MBProgressHUD showContent:@"赠送成功" toView:self.view];
                }
                [[NSNotificationCenter defaultCenter] postNotificationName:BMHRefreshUserInfo object:nil];
                
            }else if (x) {
                [self.keyboardView removeFromSuperview];
                
                [HelpTool startTipViewWithText:@"余额不足" duration:1 type:kTipViewTypeNone];
                
                
            }else {
                self.isEnderMoney = NO;
                TopUpViewController *topVC = [[TopUpViewController alloc] initWithBeautyid:[[NSUserDefaults standardUserDefaults] objectForKey:UserID]];
                topVC.In_purchase = NO;
                topVC.backActionBlock = ^() {
                    [self dismissViewControllerAnimated:YES completion:NULL];
                };
                UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:topVC];
                
                [self presentViewController:nav animated:YES completion:nil];
            }
        } error:^(NSError *error) {
            _giftAnimalFinish = YES;
            [HelpTool startTipViewWithText:[error.userInfo objectForKey:@"NSLocalizedDescription"] duration:2.0f type:kTipViewTypeNone];
        }];
    }else{
        
    }
    
}


#pragma mark - **********展开话题
- (void)showChatChemeView:(UIButton *)sender {
    [_TalkThemeSheetView removeFromSuperview];
    _TalkThemeSheetView = [[XLTalkThemeSheetView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    @weakify(self);
    _TalkThemeSheetView.block = ^(NSString *themeId) {
        @strongify(self);
        [self getQuestionWithThemeId:themeId];
    };
    [_TalkThemeSheetView getChatThemeListReloadData1:_callid];
    [_TalkThemeSheetView show];
    
}
#pragma mark - **********获取聊天的问题
- (void)getQuestionWithThemeId:(NSString *)themeId{
    NSDictionary *dic = @{@"callId":_callid,@"typeId":themeId,@"sendId":[[XLAccountManager shareInstance]model].Id,@"receiveId":_peerId};
    if (_Animalfinish == YES) {
        [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/api/v2/VideoChat/GetTopic" parameters:dic resultClass:nil]subscribeNext:^(id x) {
            //发送问题
            if (![x isKindOfClass:[NSNull class]]) {
                IMAMsg *msgs = [IMAMsg msgWithCustom:9 chatQuestion:x[@"Content"]];
                [self giftMessageOfsenderComment:msgs];
                [self amimalChatQuestion:x[@"Content"]];
            }
        } error:^(NSError *error) {
            
        }];
    }else{
        [MBProgressHUD showContent:@"操作太快了哦!" toView:self.view];
    }
}
- (void)amimalChatQuestion:(NSString *)QUESTION{
    _Animalfinish = NO;
    UILabel *ChatQuestonLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, ScreenHeight/2-50, ScreenWidth-60, 100)];
    ChatQuestonLabel.textAlignment = NSTextAlignmentCenter;
    ChatQuestonLabel.textColor = [UIColor whiteColor];
    ChatQuestonLabel.text = QUESTION;
    ChatQuestonLabel.font = [UIFont systemFontOfSize:25 weight:UIFontWeightHeavy];
    ChatQuestonLabel.numberOfLines = 2;
    [self.view addSubview:ChatQuestonLabel];
    ChatQuestonLabel.transform = CGAffineTransformMakeScale(0.5, 0.5);
    [self.TalkThemeSheetView removeFromSuperview];
    [UIView animateWithDuration: 0.9 delay:0 usingSpringWithDamping:0.3 initialSpringVelocity:0.2 options:0 animations:^{
        ChatQuestonLabel.transform = CGAffineTransformMakeScale(1.2, 1.2);
    } completion:^(BOOL finished) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                _Animalfinish = YES;
                [ChatQuestonLabel removeFromSuperview];
            });
        });
    }];
}
- (void)onBtnBeautyClicked {
    _vBeauty.hidden = !_vBeauty.hidden;
}

- (void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (_vBeauty.hidden == NO)
    {
        UITouch *touch = [[event allTouches] anyObject];
        CGPoint _touchPoint = [touch locationInView:self.view];
        if (NO == CGRectContainsPoint(_vBeauty.frame, _touchPoint))
        {
            [self onBtnBeautyClicked];
        }
    }
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"dealloc %@", [self class]);
}


#pragma mark -
#pragma mark - 拒绝API
/**
 拒绝API
 
 @param sender 被叫拒绝
 */
- (void)handleCloseBtn:(UIButton *)sender {
    __weak typeof(self) ws = self;
    
    if (self.isring == YES) {
        [self addBtnDidType:@"9" andAtype:@"2"];
        [self messageOfsenderComment:2];//主播拒绝
        
        [self.call refuse:^(TILCallError *err) {
            [ws stop];
            [self callMakeEndCall:@"3"];
            ws.call = nil;
//            if (_closeLab.text.length > 2) {
//                XLHostSideIncomeDetailsVC *vc = [[XLHostSideIncomeDetailsVC alloc]initWithNibName:@"XLHostSideIncomeDetailsVC" bundle:nil];
//                vc.timeString = _closeLab.text;
//
//                vc.callid = _callid;vc.toUserId = _peerId;vc.headerImageUrl = _peermodel.headimg;
//                UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:vc];
//
//                [ws presentViewController:nav animated:YES completion:^{
//
//                }];
//            }else{
                [ws dismissViewControllerAnimated:YES completion:nil];
                
//            }
        }];
        
    }else {
        [self callMakeEndCall:@"8"];
        [self messageOfsenderComment:3];//主播挂断
        
        [self.call hangup:^(TILCallError *err) {
            [ws.recvtimer pause];
            ws.call = nil;
//            if (_closeLab.text.length > 2) {
//                XLHostSideIncomeDetailsVC *vc = [[XLHostSideIncomeDetailsVC alloc]initWithNibName:@"XLHostSideIncomeDetailsVC" bundle:nil];
//                vc.timeString = _closeLab.text;
//
//                vc.callid = _callid;vc.toUserId = _peerId;vc.headerImageUrl = _peermodel.headimg;
//                UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:vc];
//
//                [ws presentViewController:nav animated:YES completion:^{
//
//                }];
//            }else{
                [ws dismissViewControllerAnimated:YES completion:nil];
                
//            }
        }];
    }
}

#pragma mark -
- (void)handleCinemaBtn:(UIButton *)sender {
    ILiveRoomManager *manager = [ILiveRoomManager getInstance];
    [manager switchCamera:^{
        
        
    } failed:^(NSString *moudle, int errId, NSString *errMsg) {
        
        
    }];
    
}

#pragma mark - 接收按钮--Action

/**
 接受呼叫-事件处理
 
 @param sender sender
 */
- (void)handleRecOrMicButton:(UIButton *)sender {
    
    UIButton * recvOrMicBtn = (UIButton *)sender;
    recvOrMicBtn.enabled = NO;
    
    if (self.isring == YES) {
        //        [[[BMHAPIManager sharedStatManager] gatherActionId:@"301" userId:[BMHAccountManager shareInstance].userInfoModel.userid channelId:nil] subscribeNext:^(id x) {
        //
        //        } error:^(NSError *error) {
        //
        //        }];
        
        if ([self checkCameraAuthorization] && [self checkMiroPhone] )
        {
            
            [self recvCall];
            
        }else{
            
            [self CameraIsOrOn];
        }
        
    }else {
        
        recvOrMicBtn.enabled = YES;
        [self handleMicButton:recvOrMicBtn];
        
    }
    
}
- (BOOL)checkPermission{
    
    //    AVAudioSessionRecordPermission permission = [[AVAudioSession sharedInstance] recordPermission];
    //    return permission == AVAudioSessionRecordPermissionGranted;
    __block BOOL bCanRecord = YES;
    if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 7.0) {
        AVAuthorizationStatus videoAuthStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
        if (videoAuthStatus == AVAuthorizationStatusNotDetermined) {// 未询问用户是否授权
            AVAudioSession *audioSession = [AVAudioSession sharedInstance];
            if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
                [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                    if (granted) {
                        bCanRecord = YES;
                    } else {
                        bCanRecord = NO;
                    }
                }];
            }
        } else if(videoAuthStatus == AVAuthorizationStatusRestricted || videoAuthStatus == AVAuthorizationStatusDenied) {
            // 未授权
            //            [self showSetAlertView];
        } else{
            // 已授权
            NSLog(@"已授权");
        }
    }
    return bCanRecord;
}
#pragma mark 切换麦克风
- (void)handleMicButton:(UIButton *)sender {
    
    ILiveRoomManager *manager = [ILiveRoomManager getInstance];
    BOOL isOn = [manager getCurMicState];
    if (isOn == YES) {
        _micLab.text = @"已静音";
        [_micButton setImage:[UIImage imageNamed:@"video_icon_quite_s"] forState:UIControlStateNormal];

    }else{
        _micLab.text = @"静音";
        [_micButton setImage:[UIImage imageNamed:@"video_icon_quite_n"] forState:UIControlStateNormal];

    }
    [manager enableMic:!isOn succ:^{
        
    } failed:^(NSString *moudle, int errId, NSString *errMsg) {
        
    }];
    
}
#pragma mark 扬声器
- (void)handleSpeakerButton:(UIButton *)sender {
    
    ILiveRoomManager *manager = [ILiveRoomManager getInstance];
    BOOL isOn = [manager getCurSpeakerState];
    if (isOn == YES) {
        _miantiLab.text = @"听筒";
        [_miantiButton setImage:[UIImage imageNamed:@"video_icon_handfree_s"] forState:UIControlStateNormal];

    }else{
        _miantiLab.text = @"免提";
        [_miantiButton setImage:[UIImage imageNamed:@"video_icon_handfree_n"] forState:UIControlStateNormal];

    }
    [manager enableSpeaker:!isOn succ:^{
        
    } failed:^(NSString *moudle, int errId, NSString *errMsg) {
        
    }];
    
}
#pragma mark -

#pragma mark - 接受方通话配置

- (void)initCall{
    TILCallConfig * config = [[TILCallConfig alloc] init];
    TILCallBaseConfig * baseConfig = [[TILCallBaseConfig alloc] init];
    baseConfig.callType = TILCALL_TYPE_AUDIO;
    baseConfig.isSponsor = NO;
    baseConfig.peerId = _invite.sponsorId;
    baseConfig.heartBeatInterval = 5;
    baseConfig.autoHdAudio = YES;
    baseConfig.autoCamera = NO;
    baseConfig.autoMic = YES;
    baseConfig.autoSpeaker = NO;
    baseConfig.isAutoResponseBusy = YES;
    config.baseConfig = baseConfig;
    
    TILCallListener * listener = [[TILCallListener alloc] init];
    listener.callStatusListener = self;
    //注意：
    //［通知回调］可以获取通话的事件通知，建议双人和多人都走notifListener
    // [通话状态回调] 也可以获取通话的事件通知
    listener.memberEventListener = self;
    listener.notifListener = self;
    
    config.callListener = listener;
    
    TILCallResponderConfig * responderConfig = [[TILCallResponderConfig alloc] init];
    responderConfig.controlRole = @"userB";
    responderConfig.callInvitation = _invite;
    config.responderConfig = responderConfig;
    _call = [[TILC2CCall alloc] initWithConfig:config];
    
}
#pragma mark -
#pragma mark - 接收方-接受通话成功
/**
 接收方 -接受通话建立成功
 */
- (void)recvCall{
    __weak typeof(self) ws = self;
    [ws stop];
    [_call createRenderViewIn:self.view];
    @weakify(self);
    [self.call accept:^(TILCallError *err) {
        @strongify(self);
        if(err){
            NSLog(@"接受失败:%@-%d-%@",err.domain,err.code,err.errMsg);
            self.jietingButton.enabled = YES;
            [HelpTool startTipViewWithText:@"对方已挂断!" duration:2.0f type:kTipViewTypeNone];
            [self selfDismiss];
        }
        else{
            [_launchAnimation stop];
            [_launchAnimation removeFromSuperview];
            self.detailLabel.hidden = YES;
            
            self.jietingButton.enabled = YES;
            self.jietingButton.hidden = YES;
            ws.errLabel.hidden = YES;
            self.isReceived = YES;
             _chatThemeBtn.hidden = NO;
            self.giftBtn.hidden = NO;
            self.micButton.hidden = NO;
            self.micLab.hidden = NO;
            self.miantiButton.hidden = NO;
            self.miantiLab.hidden = NO;
            self.inforLabel.hidden = NO;
            if (_isfollow == NO) {
                self.followButton.hidden = NO;
            }
            self.nameLabel.frame = CGRectMake(0, _headImae.frame.origin.y + 135, ScreenWidth, 20);
            self.nameLabel.textAlignment = NSTextAlignmentCenter;
            self.inforLabel.frame = CGRectMake(0, _headImae.frame.origin.y + 160, ScreenWidth, 20);

            [self onCallEstablishddd];
            //            [self handleRecevBaseTap:nil];
            
        }
    }];
//    [self.call createRenderViewIn:self.view];
//    UIView *baseView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 140, 40, 120, 160)];
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleRecevBaseTap:)];
//    [baseView addGestureRecognizer:tap];
//    [self.view addSubview:baseView];
}
#pragma mark - 成员有视频流事件

/**
 成员有视频流事件
 @param isOn    YES 开启视频流
 @param members TILCallMember*列表
 */
- (void)onMemberCameraVideoOn:(BOOL)isOn members:(NSArray *)members{
//    if(isOn){
//        for (TILCallMember *member in members) {
//            NSString *identifier = member.identifier;
//            if([identifier isEqualToString:_myId]){
//                [_call addRenderFor:_myId atFrame:self.view.bounds];
//                [_call sendRenderViewToBack:_myId];
//            }else{
//                [_call addRenderFor:identifier atFrame:CGRectMake(SCREEN_WIDTH - 135, 50, 120, 160)];
//                
//            }
//        }
//    }
//    else{
//        [HelpTool startTipViewWithText:@"对方关闭摄像头" duration:2.0f type:kTipViewTypeNone];
//        for (TILCallMember *member in members) {
//            NSString *identifier = member.identifier;
//            [_call removeRenderFor:identifier];
//        }
//    }
}

- (void)handleRecevBaseTap:(UITapGestureRecognizer *)sender {
    
    [_call switchRenderView:_invite.sponsorId with:_myId];
    
}
//设置按钮是否可用
- (void)setButtonEnable:(BOOL)isAccept{
    self.isring = isAccept;
    self.cinemaBtn.hidden = YES;
    self.cinemaLab.hidden = YES;
    self.giftBtn.hidden = isAccept;
    self.giftLab.hidden = isAccept;
}
-(void)timerLabel:(MZTimerLabel*)timerLabel countingTo:(NSTimeInterval)time timertype:(MZTimerLabelType)timerType{
    NSString *second = [NSString stringWithFormat:@"%f",time];
    NSString *second2 = [[second componentsSeparatedByString:@"."]firstObject];
    NSInteger integer = [second2 integerValue] % (5);
    if ([second2 integerValue] > 0 && integer == 0) {
        [self koufei];
    }
    NSLog(@"33333333333333%f",time);
    NSLog(@"44444444444444%@",timerLabel.text);
}

#pragma mark - 扣费
- (void)koufei{
    NSDictionary *dic = @{@"type":@"1",
                          @"userId":[[XLAccountManager shareInstance]model].Id,
                          @"anchorId":_peerId,
                          @"callId":_callid
                          };
    [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/Api/v2/VideoChat/Connect1v1Charge" parameters:dic resultClass:nil] subscribeNext:^(id x) {
    } error:^(NSError *error) {
        if (error.code == 6) {
            [self callMakeEndCall:@"9"];
            [self selfDismiss];
        }
    }];
}
//消息事件
- (void)onCallEstablishddd{
    self.jietingLab.hidden = YES;
    [self stop];
    self.recvtimer = [[MZTimerLabel alloc] initWithLabel:self.closeLab andTimerType:MZTimerLabelTypeStopWatch];
    self.recvtimer.delegate = self;
    [self.recvtimer start];
    _closeLab.frame = CGRectMake(SCREEN_WIDTH - 80 , 30, 60, 20);
    _closeBtn.frame = CGRectMake(10, 30, 40, 40);
    [_closeBtn setImage:[UIImage imageNamed:@"video_icon_chacha_n1"] forState:UIControlStateNormal];
    
    __weak typeof(self) ws = self;
    
    [self performSelector:@selector(heartbeatCallup) withObject:nil afterDelay:20];
    AVAudioSession * session = [AVAudioSession sharedInstance];
    NSError *sessionError = nil;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    
    UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    AudioSessionSetProperty (
                             kAudioSessionProperty_OverrideAudioRoute,
                             sizeof (audioRouteOverride),
                             &audioRouteOverride
                             );
#pragma clang diagnostic pop
    if(!session) {
        DebugLog(@"Error creating session: %@", [sessionError description]);
    }
    else {
        [session setActive:YES error:nil];
    }
    ILiveRoomManager *manager = [ILiveRoomManager getInstance];
    BOOL isOn = [manager getCurMicState];
    [ws.jietingButton setImage:[UIImage imageNamed:isOn ?@"videoMicClose":@"videoMicOpen"] forState:UIControlStateNormal];
    //    ws.micLab.text = isOn ?@"切换摄像头":@"切换摄像头";
    [manager setAudioMode:QAVOUTPUTMODE_SPEAKER];
    
    [self setButtonEnable:NO];
    
}


#pragma mark - 事件通知类型
/**
 事件通知类型
 */
- (void)onRecvNotification:(TILCallNotification *)notify{
    NSInteger notifId = notify.notifId;
    switch (notifId) {
        case TILCALL_NOTIF_CANCEL: {
            [self selfDismiss];
            [HelpTool startTipViewWithText:@"对方取消邀请" duration:2.0f type:kTipViewTypeNone];
        }
            break;
        case TILCALL_NOTIF_TIMEOUT: {
            [self selfDismiss];
            [HelpTool startTipViewWithText:@"对方呼叫超时" duration:2.0f type:kTipViewTypeNone];
        }
            break;
        case TILCALL_NOTIF_HANGUP: {
            [self selfDismiss];
            [HelpTool startTipViewWithText:@"对方已挂断" duration:2.0f type:kTipViewTypeNone];
        }
            break;
        case TILCALL_NOTIF_HEARTBEAT: {
            if (self.isReceived) {
                [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(heartbeatCallup) object:nil];
                [self performSelector:@selector(heartbeatCallup) withObject:nil afterDelay:20];
            }
        }
            break;
        case TILCALL_NOTIF_DISCONNECT: {
            [self selfDismiss];
            [HelpTool startTipViewWithText:@"失去连接" duration:2.0f type:kTipViewTypeNone];
        }
            break;
        default:
            break;
    }
}
#pragma mark -
-(void)getFlowerList{
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"5", @"type",nil];
    [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/Api/v2/Gift/GetGiftList" parameters:dic resultClass:nil] subscribeNext:^(id x) {
        [self getSenderGiftArr:x];
    } error:^(NSError *error) {
        
    }];
}
- (void)getSenderGiftArr:(NSMutableArray *)arr {
    for (int i = 0; i < arr.count; i++) {
        GiftModel *giftModer = [[GiftModel alloc] initWithDict:arr[i]];
        [self.senderGiftArr addObject:giftModer];
    }
    [self.view reloadInputViews];
}


/**
 发送消息
 
 @param commentTag
 */
- (void)messageOfsenderComment:(int)commentTag {
    
    NSDictionary *myInfoDic = [NSDictionary dictionaryWithObjectsAndKeys:@(commentTag), @"command",self.peerId,@"callId",[[NSUserDefaults standardUserDefaults] objectForKey:UserID],@"rejectId",nil];
    NSString * jsonStr = [self dictionaryToJson:myInfoDic];
    NSLog(@"gangjinru == %@", myInfoDic);
    NSDictionary *groupDic = [NSDictionary dictionaryWithObjectsAndKeys:@(12),@"action",jsonStr,@"videoPhoneMessage", nil];
    TIMMessage *msg = [[TIMMessage alloc] init];
    TIMCustomElem *elem = [[TIMCustomElem alloc] init];
    elem.data = [NSJSONSerialization dataWithJSONObject:groupDic options:NSJSONWritingPrettyPrinted error:nil];
    [msg addElem:elem];
    TIMConversation *con = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:_peerId];
    [con sendMessage:msg succ:^{
    } fail:^(int code, NSString *msg) {
        
    }];
}
- (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

- (void)giftMessageOfsenderComment:(IMAMsg *)msg {
    [_conversation sendMessage:msg completion:^(NSArray *imamsgList, BOOL succ, int code) {
        
    }];
    TIMElem *meaage = [msg.msg getElem:0];
    if ([meaage isKindOfClass:[TIMCustomElem class]]) {
        TIMCustomElem *elem = (TIMCustomElem *)[msg.msg getElem:0];
        CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
        if (elemCmd.msgType == 3) {
            if ([elemCmd.giftMsgImage rangeOfString:@"gif"].location != NSNotFound ) {
//                [self addGifPicWithIndexXX:elemCmd.giftBubbleImage withName:elemCmd.giftName];
                
            }else {
//                [self addGifImageView:elemCmd.giftMsgImage withName:elemCmd.giftName];
                
            }
        }else if (elemCmd.msgType == 9){
            //            self.ChatQuestonLabel.text = elemCmd.chatQuestion;
            //            [self amimalChatQuestion:elemCmd.chatQuestion];
        }
        
    }
    
}
//- (void)addGifImageView:(NSString *)gifStr  withName:(NSString *)namestr{
//    MagMeaageModel *magMessageModel = [[MagMeaageModel alloc] init];
//    magMessageModel.giftCount = 1;
//    magMessageModel.senderId = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
//    magMessageModel.giftImageUrl = gifStr;
//    magMessageModel.giftName = namestr;
//    ChatOperationManage *gifmanager = [ChatOperationManage sharedManager];
//    gifmanager.parentView = self.view;
//    // 用用户唯一标识 msg.senderChatID 存礼物信息,model 传入礼物模型
//    [gifmanager animWithUserID: magMessageModel.giftMoveImageUrl model:magMessageModel finishedBlock:^(BOOL result) {
//
//    }];
//}
//
//- (void)addGifPicWithIndexXX:(NSString *)gifStr withName:(NSString *)namestr{
//    MagMeaageModel *magMessageModel = [[MagMeaageModel alloc] init];
//    magMessageModel.giftCount = 1;
//    magMessageModel.senderId = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
//    magMessageModel.giftMoveImageUrl = gifStr;
//    magMessageModel.giftName = namestr;
//    GifAniOpertaionManager *gifmanager = [GifAniOpertaionManager sharedManager];
//    gifmanager.parentView = self.view;
//    // 用用户唯一标识 msg.senderChatID 存礼物信息,model 传入礼物模型
//    [gifmanager animWithUserID: magMessageModel.giftMoveImageUrl model:magMessageModel finishedBlock:^(BOOL result) {
//
//    }];
//}

- (void)hide{
    
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
   
    } completion:^(BOOL finished)
     {
         [self.keyboardView removeFromSuperview];
     }];
}

#pragma mark - 通话相关API

/**
 后台统计通话API
 
 @param type  主叫和被叫
 @param atype 通话挂断类型
 */
- (void)addBtnDidType:(NSString *)type andAtype:(NSString *)atype {
    //type=9&userId=&anchorId=&callId=&aType=
    
    NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
    NSString *peeridStr = self.peerId;
    //令牌
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    
    NSString *sTimeUser = [fmt stringFromDate:now];
    NSString *objIDUser = @"0";
    NSString *publicKeyUser = @"BMH2014YDYWB";
    NSString *natUser = [NSString stringWithFormat:@"%@%@%@%@%@",objIDUser,uid,peeridStr, publicKeyUser, sTimeUser];
    natUser = [natUser md5Encrypt];
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
                         type, @"type",
                         atype, @"aType",
                         NSUser_object(UserID), @"anchorId",
                         self.peerId, @"userId",
                         [NSString stringWithFormat:@"%d", self.peermodel.newRecordId], @"callId",
                         natUser, @"appsign",
                         nil];
    
    [BMHHTTPSession GET:@"MobileInterface/PayVoiceVideo/PayVoiceVideo.ashx" paraments:dic success:^(id  _Nullable JSON) {
        NSLog(@"flowwwww == %@",JSON);
    } failure:^(NSError * _Nullable error) {
        
    }];
}

#pragma mark - 主播通话挂断相关
-(void)callMakeEndCall:(NSString *)endType
{
    
    [[[XLHTTPSessionManager sharedManager] getVideoChatEndCallID:_callid userId:self.peerId anchorId:NSUser_object(UserID) endType:endType] subscribeNext:^(id x) {
        
        NSLog(@"callid***********%d,endtype%@",self.peermodel.newRecordId,endType);
        
    } error:^(NSError *error) {
        
    }];
}

#pragma mark - 心跳API
/**
 心跳API 每20s发送一次心跳
 */
//-(void)everyHeartBeat:(id)sender
//{
//    NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
//    NSString *callVideoID = [[NSUserDefaults standardUserDefaults] objectForKey:kVideoID];
//    NSString *peeridStr = self.peerId;
//    //令牌
//    NSDate *now = [NSDate date];
//    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
//    fmt.dateFormat = kBMHRequestTimeFormat;
//
//    NSString *sTimeUser = [fmt stringFromDate:now];
//    NSString *objIDUser = @"0";
//    NSString *publicKeyUser = @"BMH2014YDYWB";
//    NSString *natUser = [NSString stringWithFormat:@"%@%@%@%@%@",objIDUser,uid,peeridStr, publicKeyUser, sTimeUser];
//    natUser = [natUser md5Encrypt];
//
//    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
//                                                                 @"11", @"type",
//         [NSString stringWithFormat:@"%d", self.peermodel.newRecordId], @"callId",
//                                                 NSUser_object(UserID), @"anchorId",
//                                                           self.peerId, @"userId",
//                                                                  @"2", @"iFlag",
//                                                               natUser, @"appsign",
//                                                                nil];
//
//    [BMHHTTPSession GET:@"MobileInterface/PayVoiceVideo/PayVoiceVideo.ashx" paraments:dic success:^(id  _Nullable JSON) {
//
//        BMHLog(@"被叫方心跳 == %@",JSON);
//        NSString  *status  =  JSON[@"result"][@"data"];
//
//        if ([[NSString stringWithFormat:@"%@",status] isEqualToString:@"0"]) {
//
//            [self heartbeatCallupAPI];
//        }
//    } failure:^(NSError * _Nullable error) {
//
//    }];
//
//
//}

#pragma mark - 心跳停止 -挂断API

/**
 心跳停止 -挂断API
 */
-(void)heartbeatCallup
{
    [HelpTool startTipViewWithText:@"对方网络已断" duration:2.0f type:kTipViewTypeNone];
    [self callMakeEndCall:@"12"];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(heartbeatCallup) object:nil];
    [self selfDismiss];
}

/**
 摄像头权限关闭 -接受执行挂断API
 */
-(void)CameraIsOrOn
{
    __weak typeof(self) ws = self;
    
    
    [ws dismissViewControllerAnimated:YES completion:nil];
    [self addBtnDidType:@"9" andAtype:@"2"];
    [self messageOfsenderComment:2];//主播拒绝
    [self.call refuse:^(TILCallError *err) {
        [ws stop];
        ws.call = nil;
        [ws dismissViewControllerAnimated:YES completion:nil];
    }];
}


- (void)selfDismiss
{
    self.isEnderMoney = YES;
    [_vBeauty saveValues];
    __weak typeof(self) ws = self;
    
    [ws stop];
    [ws.recvtimer pause];
    ws.call = nil;
    [ws.heartChcek invalidate];
    ws.heartChcek = nil;
    [ws dismissViewControllerAnimated:YES completion:nil];
    
    [self.call hangup:^(TILCallError *err) {
        
        if(err){
            BMHLog(@"挂断失败");
        }
        else{
            BMHLog(@"挂断成功");
        }
        //老代码挂断后的操作要在挂断结果中处理
//        [ws stop];
//        [ws.recvtimer pause];
//        ws.call = nil;
//        [ws.heartChcek invalidate];
//        ws.heartChcek = nil;
//        [ws dismissViewControllerAnimated:YES completion:nil]
        
        
        
        
        
//        if (_closeLab.text.length > 2) {
//            XLHostSideIncomeDetailsVC *vc = [[XLHostSideIncomeDetailsVC alloc]initWithNibName:@"XLHostSideIncomeDetailsVC" bundle:nil];
//            vc.timeString = _closeLab.text;
//
//            vc.callid = _callid;vc.toUserId = _peerId;vc.headerImageUrl = _peermodel.headimg;
//            UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:vc];
//            [ws presentViewController:nav animated:YES completion:^{
//
//            }];
//        }else{
//            [ws dismissViewControllerAnimated:YES completion:nil];
//        }
    }];
    
}

#pragma mark - 检测相机
- (BOOL)checkCameraAuthorization {  //检测相机是否可用和有无授权
    BOOL isCameraAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    if (!isCameraAvailable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前设备无法使用摄像头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return isCameraAvailable;
    }
    BOOL isAvalible = YES;
    //ios 7.0以上的系统新增加摄像头权限检测
    if (iOS7) {
        //获取对摄像头的访问权限。
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        switch (authStatus) {
            case AVAuthorizationStatusRestricted://此应用程序没有被授权访问的照片数据。可能是家长控制权限。
                break;
            case AVAuthorizationStatusDenied://用户已经明确否认了这一照片数据的应用程序访问.
                isAvalible = NO;
                break;
            case AVAuthorizationStatusAuthorized://用户已授权应用访问照片数据.
                break;
            case AVAuthorizationStatusNotDetermined://用户尚未做出了选择这个应用程序的问候
                isAvalible =[UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
                break;
            default:
                break;
        }
    }
    if (!isAvalible) {
        [HelpTool startTipViewWithText:@"您的相机权限未开启，请设置" duration:2.0f type:kTipViewTypeNone];
    }
    return isAvalible;
}

#pragma mark - TXIVideoPreprocessorDelegate
- (void)didProcessFrame:(Byte *)bytes width:(NSInteger)width height:(NSInteger)height format:(TXEFrameFormat)format timeStamp:(UInt64)timeStamp
{
    self.processorBytes = bytes;
}

- (void)onDetectFacePoints:(NSArray *)points {
    
}

#pragma mark - 屏幕方向改变
- (BOOL)shouldAutorotate
{
    return NO;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return  UIInterfaceOrientationPortrait;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (BOOL)checkMiroPhone {
    BOOL isA;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    switch (authStatus) {
        case AVAuthorizationStatusNotDetermined:
            isA = NO;
            break;
        case AVAuthorizationStatusRestricted:
            isA = NO;
            break;
        case AVAuthorizationStatusDenied:
            isA = NO;
            break;
        case AVAuthorizationStatusAuthorized:
            isA = YES;
            break;
        default:
            isA = NO;
            break;
    }
    if (isA == NO) {
        [HelpTool startTipViewWithText:@"您的麦克风权限未开启，请设置" duration:2.0f type:kTipViewTypeNone];
    }
    return isA;
}
- (void)reaciveGiftMessage:(NSNotification *)infor{
    IMAMsg *msg = infor.object;
    TIMCustomElem *elem = (TIMCustomElem *)[msg.msg getElem:0];
    CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
    NSDictionary *giftdic = [NSJSONSerialization JSONObjectWithData:elem.data options:0 error:nil];
    NSString *urlStringMove = elemCmd.giftBubbleImage;
    NSString *urlStringImg = elemCmd.giftMsgImage;
    NSString *idGift = [NSString stringWithFormat:@"%@",giftdic[@"giftId"]];
    CGFloat durition = 0.0;
    if ([idGift integerValue] == 110 || [idGift integerValue] == 111 || [idGift integerValue] == 112) {
        durition =  4.6;
    }else{
        durition = 8.5;
    }
    if (![idGift isEqualToString:@"109"] && ![idGift isEqualToString:@"89"]){//不是么么哒动画
        if (![urlStringMove isKindOfClass:[NSNull class]] && urlStringMove.length > 0) {//moveimage有数据
            if ([urlStringMove rangeOfString:@"webp"].location != NSNotFound){
                //读取
                NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
                NSString *fileName = [[urlStringMove componentsSeparatedByString:@"/"]lastObject];
                NSString *imageFilePath = [path stringByAppendingPathComponent:fileName];
                NSError * error;
                NSData * data = [NSData dataWithContentsOfFile:imageFilePath options:NSDataReadingMappedIfSafe error:&error];
                if (data) {
                    UIImageView * imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
                    [self.view addSubview:imageV];
                    UIImage * image = [UIImage sd_imageWithWebPData:data];
                    imageV.image = image;
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(durition * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [imageV removeFromSuperview];
                            _giftAnimalFinish = YES;
                        });
                    });
                }else{
                    NSLog(@"惨啦，没有拿到数据");
                    [self downloadWebp:urlStringMove time:durition];
                }
            }else{//webp不为空的普通动画
//                [self addGifImageView:urlStringImg withName:elemCmd.giftName];
                _giftAnimalFinish = YES;
            }
        }else{//webp为空的普通动画
            
        }
    }else{//么么哒动画
        [self showMoreLoveAnimateFromView:nil addToView:self.view fromMe:YES];
    }
}
- (void)showMoreLoveAnimateFromView:(UIView *)fromView addToView:(UIView *)addToView fromMe:(BOOL)fromMe {
    _giftAnimalFinish = YES;
    CGFloat w = self.view.frame.size.width;
    CGFloat h = self.view.frame.size.height;
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
    
    //起点
    CGPoint position = CGPointMake(60, ScreenHeight - 60);
    
    imageView.layer.position = position;
    imageView.image = [UIImage imageNamed:@"momoda_icon"];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    [addToView addSubview:imageView];
    
    //动画总时长
    CGFloat duration = 6;
    
    //形变动画1 变大
    [UIView animateWithDuration:duration/2 animations:^{
        imageView.transform = CGAffineTransformMakeScale(2, 2);
    }];
    
    //形变动画2 还原
    [UIView animateWithDuration:duration/2 delay:duration/2 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:UIViewAnimationOptionCurveEaseIn animations:^{
        imageView.transform = CGAffineTransformIdentity;
    } completion:nil];
    
    //路径动画
    CAKeyframeAnimation *positionAnimate = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    positionAnimate.repeatCount = 1;
    positionAnimate.duration = duration;
    positionAnimate.fillMode = kCAFillModeForwards;
    positionAnimate.removedOnCompletion = NO;
    
    
    UIBezierPath *sPath = [UIBezierPath bezierPath];
    //设置三次贝塞尔曲线的起点
    [sPath moveToPoint:position];
    
    //第一个控制点
    int r1 = w - 40;//x的取值范围：[20, w - 20]
    int r2 = h - 40;//y的取值范围：[20, h - 20]
    CGPoint controlOne = CGPointMake((arc4random() % r1) + 20, (arc4random() % r2) + 20);
    UIView *p1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 5, 5)];
    p1.backgroundColor = [UIColor blueColor];
    p1.center = controlOne;
    //    [self.view addSubview:p1];
    
    //第二个控制点
    int l1 = w - 40;
    int l2 = h - 40;
    CGPoint controlTwo = CGPointMake((arc4random() % l1) + 20, (arc4random() % l2) + 20);
    UIView *p2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 5, 5)];
    p2.backgroundColor = [UIColor redColor];
    p2.center = controlTwo;
    //    [self.view addSubview:p2];
    
    //三次贝塞尔曲线的终点 （ w ，50）
    CGPoint endPoint = CGPointMake(w, 50);
    [sPath addCurveToPoint:endPoint controlPoint1:controlOne controlPoint2:controlTwo];
    positionAnimate.path = sPath.CGPath;
    
    [imageView.layer addAnimation:positionAnimate forKey:@"heartAnimated"];
    
    CAShapeLayer *l = [CAShapeLayer new];
    l.path  = sPath.CGPath;
    l.fillColor   = [UIColor clearColor].CGColor;
    l.strokeColor = [UIColor blackColor].CGColor;
    //    [self.view.layer addSublayer:l];
    
    [UIView animateWithDuration:duration animations:^{
        imageView.layer.opacity = 0;
    } completion:^(BOOL finished) {
        [imageView removeFromSuperview];
        [l removeFromSuperlayer];
        [p1 removeFromSuperview];
        [p2 removeFromSuperview];
    }];
}
- (void)downloadWebp:(NSString *)urlString time:(CGFloat)durition{
    dispatch_queue_t queue2 = dispatch_queue_create("queue", NULL);
    dispatch_async(queue2, ^{
        UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        [self.view addSubview:imageV];
        NSError * error;
        NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString] options:NSDataReadingMappedIfSafe error:&error];
        if (data) {
            UIImage * image = [UIImage sd_imageWithWebPData:data];
            imageV.image = image;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(durition * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [imageV removeFromSuperview];
                    _giftAnimalFinish = YES;
                });
            });
        }else{
            NSLog(@"惨啦，没有拿到数据");
        }
    });
}
@end
